package com.gfv.facturas.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.gfv.comunes.NombreValor;
import com.gfv.facturas.negocio.Persona;

public class PersonasDAO implements RowMapper{
	protected final Log logger = LogFactory.getLog(getClass());
	private JdbcTemplate jdbcPlant;

	private Collection getPersonas(int id, boolean esusuario)
	{
		
		Collection obj = null;
		try
		{
			obj= jdbcPlant.query(
				"SELECT * FROM PERSONAS WHERE uid=? AND esusuario=?", 
				new Object[]{id, esusuario}, 
				this);
			return obj;
		}catch(EmptyResultDataAccessException ex)
		{
			return null;
		
						
		}
	}
	public List<NombreValor> getListaPersonas(int uid)
	{
		List<NombreValor>pers=new ArrayList<NombreValor>();
		Collection col=getPersonas(uid, false);
		Persona auxiliar;
		pers.add(new NombreValor("Todas",""));
		if (col!=null)
		{
			while (col.iterator().hasNext())
			{
				auxiliar=(Persona) col.iterator().next();
				pers.add(new NombreValor(auxiliar.getNombre(), Integer.toString(auxiliar.getId())));
			}
		}
		return pers;
	}
	public Persona getDatUsuario(int id)
	{
		Collection col=getPersonas(id, true);
		//Persona persona;
		if (col!=null)
		{
			if (col.iterator().hasNext())
			{
				return(Persona) col.iterator().next();
				
			}
				
			
		}
		return null;
	}
	public void setDataSource(DataSource ds)
	{
		jdbcPlant=new JdbcTemplate(ds);
	}
	public Object mapRow(ResultSet rs, int arg1) throws SQLException {
		Persona pers=new Persona();
		pers.setId(rs.getInt("id"));
		pers.setUid(rs.getInt("uid"));
		pers.setNombre(rs.getString("nombre"));
		pers.setDom_calle(rs.getString("dom_calle"));
		pers.setDom_localidad(rs.getString("dom_localidad"));
		pers.setDom_cp(rs.getString("dom_cp"));
		pers.setDom_prov(rs.getString("dom_prov"));
		pers.setDom_pais(rs.getString("dom_pais"));
		pers.setNIF_CIF(rs.getString("NIF_CIF"));
		
		pers.setPorc_retencion(rs.getBigDecimal("Porc_retencion"));
		pers.setForma_pago(rs.getString("Nombre"));
		pers.setCcc(rs.getString("ccc"));
		pers.setEsusuario(rs.getBoolean("Nombre"));
		pers.setEshistorico(rs.getBoolean("Nombre"));
		return pers;
	}
}
